package com.fingard.dsp.bank.directbank.boc01;

import com.alibaba.fastjson.JSON;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.dsp.bank.directbank.boc01.receiptpro.BOC01TaskReceiptPro;
import com.fingard.io.FileHelper;
import com.fingard.net.FormSubmit;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.*;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

public class BOC01ScheduleTask extends BOC01Base implements IScheduleTask {
    @Override
    public void execTask(TaskTimerSet timerSet) {
        if (timerSet.taskNameList.toLowerCase().contains("pushreceipt")) {
            qryReceipt();
        }
        if (timerSet.taskNameList.toLowerCase().contains("pushcodefile")) {
            qryCodeFile();
        }
        if (timerSet.taskNameList.toLowerCase().contains("downreceiptpro")) {
            BOC01TaskReceiptPro taskReceiptPro = new BOC01TaskReceiptPro();
            taskReceiptPro.reqHeader = this.reqHeader;
            taskReceiptPro.bankFront = this.bankFront;
            taskReceiptPro.setSbLog(this.sbLog);
            taskReceiptPro.setLogFlushTime(this.logFlushTime);
            taskReceiptPro.downReceipt(timerSet);
        }
    }

    private String receiptSaveToMainDir = "";

    public void qryReceipt() {
        try {
            receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
            if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                    if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                        if (this.getBankConfig().getValueAsBool("isReceiptInterface")) {
                            pushReceiptToATS();
                        } else {
                            getStatement();
                        }
                    } else {
                        WriteBankLogLn("DSPSystem未配置回单文件推送地址");
                    }
                } else {
                    WriteBankLogLn("DSPSystem未配置回单文件共享目录");
                }
            } else {
                WriteBankLogLn("DSPSystem未配置回单文件下载保存主目录");
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        }
    }


    private void getStatement() {
        String uploadType = SmbFileUtil.getUploadType();
        try {
            List<StringBuilder> jsonList = new ArrayList<StringBuilder>();
            StringBuilder json = null;
            List<File> fileList = new ArrayList<File>();
            FtpSet ftpSet = bankFront.getFtpSet("receipt");
            if ("FTPDOWNLOAD".equals(bankFront.getStrValueByFor("receiptDownLoadType", ""))) {
                String downFilePath = ftpSet.downDir;
                WriteBankLogLn("FTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
                WriteBankLogLn("开始下载服务器文件" + downFilePath + "至本地文件" + receiptSaveToMainDir);
                FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                ftpPtClient.connect();
                ftpPtClient.list(downFilePath, ".zip");
                ArrayList<String> ftpFileList = ftpPtClient.arFiles;
                String fileStr = Format.Date8Format.format(new Date());
                StringBuilder fileNameStr = new StringBuilder();
                for (int i = 0; i < ftpFileList.size(); i++) {
                    String ftpFileName = ftpFileList.get(i);
                    if (ftpFileName.contains(fileStr) && ftpFileName.contains(".zip")) {
                        FtpReceiver tmpReceiver = ftpPtClient.downloadFile(ftpFileName,
                                receiptSaveToMainDir + ftpFileName.substring(ftpFileName.lastIndexOf("/"), ftpFileName.length()));
                        if (tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {
                            File file = new File(receiptSaveToMainDir + ftpFileName.substring(ftpFileName.lastIndexOf("/"), ftpFileName.length()));
                            fileList.add(file);
                            fileNameStr.append(file.getName());
                        }
                    }
                }
                WriteBankLogLn("FTP下载服务器文件成功：" + fileList.size() + "笔至本地文件" + receiptSaveToMainDir
                        + "，下载的文件名称为：" + fileNameStr.toString());
            } else {
                fileList = downloadFile(ftpSet);
            }
            int tmpFileCount = 0;
            boolean isSaveOnlyFile = false;
            for (int i = 0; i < fileList.size(); i++) {
                boolean isZip = true;
                if (fileList.get(i).exists()) {
                    String fileName = fileList.get(i).getName();
                    String actNum = null;
                    String tranDate = null;
                    String tmpDateFileDir = getTempFileDirectory();
                    WriteBankLogLn("解压至：" + tmpDateFileDir + File.separator + fileName);
                    ZipHelper.unzipFile(fileList.get(i).getPath(), tmpDateFileDir);

                    File receiptDir = new File(tmpDateFileDir + File.separator + fileName.replace(".zip", ""));
                    if (!receiptDir.exists()) {
                        WriteBankLogLn("不存在回单目录:" + receiptDir.getName());
                        continue;
                    }

                    File[] receiptFiles = receiptDir.listFiles();
                    if (receiptFiles != null && receiptFiles.length > 0) {
                        WriteBankLogLn(fileName + "解压后共有" + receiptFiles.length + "个文件");
                        //String actCur = fileName.split("_")[3];
                        for (File receiptFile : receiptFiles) {
                            if (receiptFile.getName().contains(fileName.replace(".zip", ""))) {
                                WriteBankLogLn("解压后pdf文件名称为：" + receiptFile.getName() + ",与压缩包名称：" + fileName + "相同，没有电子回单。");
                                isZip = false;
                            } else {
                                if (receiptFile.exists()) {
                                    File newFile = new File(receiptFile.getPath().replace("+", "_"));
                                    if (!receiptFile.renameTo(newFile)) {
                                        WriteBankLogLn("解压后pdf文件名称为：" + receiptFile.getPath() + ",修改文件名称出错");
                                        continue;
                                    } else {
                                        receiptFile = newFile;
                                    }
                                }
                                String tmpByDate = Format.Date8Format.format(new Date());
                                String[] receiptFileName = receiptFile.getName().split("_");
                                actNum = receiptFileName[1];
                                String actCur = getBankConfig().getMapValueByKey("elereceiptAccountInfo", actNum);
                                if (StringHelper.isNullOrEmpty(actCur)) {
                                    actCur = "1";
                                }
                                tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + actNum + "/";
                                tranDate = receiptFileName[0];
                                //上传文件到共享目录下
                                int result = -1;
                                String ftpFilePath = "";
                                String AtsFilePath = "";
                                if (receiptFile.exists()) {
                                    if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                        if ("smb".equals(uploadType)) {
                                            WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            result = SmbFileUtil.smbUploading(receiptFile.getPath(), tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                            AtsFilePath = tmpByDate + receiptFile.getName();
                                        } else if ("localhost".equals(uploadType)) {
                                            String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                            WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                            result = FileHelper.copyFile(receiptFile.getPath(), shareDir + tmpByDate + receiptFile.getName());
                                            AtsFilePath = tmpByDate + receiptFile.getName();
                                        } else {
                                            tmpByDate = tmpByDate.replaceAll(reqHeader.bankCode + "/", "");
                                            WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            Map<String, String> map = FormSubmit.fileUpload(FGBiz.dspCenter.dspSet.receiptShareDir, actNum, receiptFile.getPath(), tmpByDate, fileName, getCharset());
                                            WriteBankLogStep3(JSON.toJSONString(map));
                                            if (map.keySet().size() != 0) {
                                                result = Integer.valueOf(map.get("respCode"));
                                                tmpByDate = map.get("remotePath");
                                                AtsFilePath = tmpByDate;
                                            } else {
                                                result = -1;
                                            }
                                        }
                                    } else {
                                        //ftp服务器
                                        FtpSet ftpSet2 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                        WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet2.upDir);
                                        //上传ftp服务器的地址
                                        AtsFilePath = tmpByDate + receiptFile.getName();
                                        ftpFilePath = StringHelper.trimEndFileSp(ftpSet2.upDir) + "/" + AtsFilePath;
                                        WriteBankLogLn("开始将回单" + receiptDir.getPath() + "上传至" + ftpFilePath);
                                        //上传至ftp
                                        result = FtpUtil.ftpUploading(ftpSet2, receiptFile.getPath(), ftpFilePath);
                                    }
                                }
                                if (result == 0 || result == 1) {
                                    isSaveOnlyFile = true;
                                    tmpFileCount++;
                                    if (result == 0) {
                                        WriteBankLogLn("文件上传成功");
                                    } else {
                                        WriteBankLogLn("文件已存在共享目录无需重复上传");
                                    }
                                    //推送数据给ATS处理
                                    json = new StringBuilder();
                                    json.append("{");
                                    json.append("\"actNum\":\"" + actNum + "\",");
                                    json.append("\"actCur\":\"" + actCur + "\",");
                                    json.append("\"receiptCode\":\"" + receiptFileName[2].replace(".pdf", "") + "\",");//回单编号
                                    json.append("\"receiptType\":\"" + "" + "\",");//回单类型  1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                    json.append("\"receiptState\":\"" + "" + "\",");//回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                    json.append("\"oppActName\":\"" + "" + "\",");
                                    json.append("\"oppActNum\":\"" + "" + "\",");
                                    json.append("\"amount\":\"" + "" + "\",");
                                    json.append("\"moneyway\":\"" + "" + "\",");
                                    json.append("\"tranSeqNo\":\"" + receiptFileName[2].replace(".pdf", "") + "\",");
//                                    json.append("\"tranSeqNo\":\"" + receiptFileName[2].replace(".pdf", "").substring(0,receiptFileName[2].replace(".pdf", "").length()-3) + "\",");
                                    json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                    json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(tranDate)) + "\",");
                                    json.append("\"filePath\":\"" + AtsFilePath + "\",");//回单文件仓库存储路径
                                    json.append("\"fileType\":\"1\"");
                                    json.append("},");
                                    jsonList.add(json);
                                } else {
                                    WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                }
                            }
                            if (FileHelper.deleteFileIfExists(receiptFile.getPath())) {
                                WriteBankLogLn("已删除临时文件：" + receiptFile.getPath());
                            }
                        }
                        if (FileHelper.deleteFileIfExists(receiptDir.getPath())) {
                            WriteBankLogLn("已删除临时文件：" + receiptDir.getPath());
                        }
                    } else {
                        WriteBankLogLn(fileName + "解压后文件为空");
                    }
                    if (isZip) {
                        String filePath = receiptSaveToMainDir + File.separator + actNum + File.separator + tranDate + File.separator;
                        if (isSaveOnlyFile) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(new Date());
                            calendar.add(Calendar.DAY_OF_MONTH, -2);
                            if (Format.Date8Format.parse(tranDate).before(calendar.getTime())) {
                                FileHelper.writeFile(filePath + actNum + "_" + tranDate + ".txt", "", getCharset());
                            }
                        }
                        if ("true".equals(bankFront.getStrValueByFor("isSaveReceiptFile", "")) && fileList.get(i).exists()) {
                            if (actNum != null) {
                                FileHelper.mkdir(filePath);
                                FileHelper.copyFile(fileList.get(i), new File(filePath + File.separator + fileName));
                            }
                        }
                    }
                    if (FileHelper.deleteFileIfExists(fileList.get(i).getPath())) {
                        WriteBankLogLn("已删除下载的压缩包文件：" + fileList.get(i).getPath());
                    }
                } else {
                    WriteBankLogLn("文件不存在：" + fileList.get(i).getPath());
                }
            }
            if (tmpFileCount > 0 && jsonList.size() > 0) {

                String sendStr = null;
                if (this.getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                    sendStr = "tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[";
                } else {
                    sendStr = "transType=downloadreceipt&data={\"rows\":[";
                }
                StringBuilder sendJson = new StringBuilder();
                String strValue = bankFront.getStrValueByFor("receiptDataCount", "");
                if (StringHelper.isNullOrEmpty(strValue)) {
                    strValue = "500";
                }
                Integer receiptDataCount = Integer.valueOf(strValue);
                for (int i = 0; i < jsonList.size(); i++) {
                    if ((i + 1) % receiptDataCount == 0 || i == jsonList.size() - 1) {
                        jsonList.get(i).deleteCharAt(jsonList.get(i).length() - 1);
                        sendJson.append(jsonList.get(i));
                        sendJson.append("]}");
                        String[] data;
                        String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                        if ("nbGateway".equals(receiptPushType)) {
                            WriteBankLogLn("3.推送给网关的数据" + sendStr + sendJson.toString());
                            data = FormSubmit.receiptInfoSend(sendStr + sendJson.toString(), this);
                            if (data[0].length() == 0 && "ok".equals(data[1])) {
                                WriteBankLogLn("5.推送数据到网关成功" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            } else {
                                WriteBankLogLn("5.推送数据到网关失败" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            }
                        } else {
                            WriteBankLogLn("3.推送给ATS的数据" + sendJson.toString());
                            data = sendToATS(sendStr + sendJson.toString());
                            if (data[0].length() == 0 && "ok".equals(data[1])) {
                                WriteBankLogLn("5.推送数据到ATS成功" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            } else {
                                WriteBankLogLn("5.推送数据到ATS失败" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            }
                        }
                        sendJson = new StringBuilder();
                    } else {
                        sendJson.append(jsonList.get(i));
                    }
                }
                WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }

        } catch (Exception e) {
            WriteBankLogLn(e);
        }
    }

    public void pushReceiptToATS() {
        String uploadType = SmbFileUtil.getUploadType();
        try {
            List<File> fileList = new ArrayList<File>();
            List<StringBuilder> jsonList = new ArrayList<StringBuilder>();
            StringBuilder json = null;
            String receiptCodeTime = this.getBankConfig().getValueAsString("receiptCodeTime");
            FtpSet ftpSet = bankFront.getFtpSet("receipt");
            if ("FTPDOWNLOAD".equals(bankFront.getStrValueByFor("receiptDownLoadType", ""))) {
                String downFilePath = ftpSet.downDir;
                WriteBankLogLn("FTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
                WriteBankLogLn("开始下载服务器文件" + downFilePath + "至本地文件" + receiptSaveToMainDir);
                FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                ftpPtClient.connect();
                ftpPtClient.list(downFilePath, ".pdf");
                ArrayList<String> ftpFileList = ftpPtClient.arFiles;
                String fileStr = Format.Date8Format.format(new Date());
                StringBuilder fileNameStr = new StringBuilder();
                for (int i = 0; i < ftpFileList.size(); i++) {
                    String ftpFileName = ftpFileList.get(i);
                    if (ftpFileName.contains(fileStr) && ftpFileName.contains(".pdf")) {
                        FtpReceiver tmpReceiver = ftpPtClient.downloadFile(ftpFileName, receiptSaveToMainDir
                                + ftpFileName.substring(ftpFileName.lastIndexOf("/"), ftpFileName.length()));
                        if (tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {
                            File file = new File(receiptSaveToMainDir
                                    + ftpFileName.substring(ftpFileName.lastIndexOf("/"), ftpFileName.length()));
                            fileList.add(file);
                            fileNameStr.append(file.getName());
                        }
                    }
                }
                WriteBankLogLn("FTP下载服务器文件成功：" + fileList.size() + "笔至本地文件" + receiptSaveToMainDir + "，下载的文件名称为："
                        + fileNameStr.toString());
            } else {
                fileList = downloadFile(ftpSet);
            }
            //返回到ATS的请求String
            int tmpFileCount = 0;
            for (int i = 0; i < fileList.size(); i++) {

                if (fileList.get(i).exists()) {
                    String fileName = fileList.get(i).getName();
                    WriteBankLogLn("读取到的批次PDF文件名为" + fileName);
                    String actNum = null;
                    //获取账号
                    String recordPath = receiptSaveToMainDir;
                    String[] files = FileHelper.listFiles(recordPath);
                    WriteBankLogLn("文件列表名称：" + files.toString());
                    if (files.length > 0) {
                        for (String f : files) {
                            if (f.contains("_") && f.contains(".txt") && f.contains(fileName.replace(".pdf", ""))) {
                                actNum = f.split("_")[0];
                                WriteBankLogLn("该批次回单账号为：" + actNum);
                            }
                        }
                    }
                    String filePath = receiptSaveToMainDir + File.separator + fileName;
                    File file_p = new File(filePath);
                    if (file_p.exists()) {
                        // String actCur = fileName.split("_")[3];
                        String tmpByDate = Format.Date8Format.format(new Date());
                        String[] receiptFileName = file_p.getName().split("_");
                        if (actNum == null) {
                            actNum = receiptFileName[0];
                        }
                        String actCur = getBankConfig().getMapValueByKey("elereceiptAccountInfo", actNum);
                        if (StringHelper.isNullOrEmpty(actCur)) {
                            actCur = "1";
                        }
                        tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                + reqHeader.bankCode + "/" + actNum + "/";
                        // 上传文件到共享目录下
                        int result = -1;
                        String ftpFilePath = "";
                        String filePath2 = "";
                        WriteBankLogLn("正在解析PDF：路径为" + file_p.getPath());
                        // 分割pdf 并以回单名称命名
                        String[] params = {"交易渠道：", "交易流水号：", "经办：", "回单编号：", "回单验证码", "打印次数：", "日期：", "付款人账号", "Transaction Date：", "扣款人账号Debit"};
                        @SuppressWarnings("unchecked")
                        List<String> fileNames = PdfGenerateUtil.splitPDF(file_p.getPath(), params);
                        // 回单重新命名
                        if (fileNames != null) {
                            for (String file : fileNames) {
                                String newFile = file_p.getPath().substring(0, file_p.getPath().lastIndexOf(".pdf")) + "/" + file;
                                String AtsFilePath = "";
                                if (newFile.contains(".pdf")) {
                                    if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                        if ("smb".equals(uploadType)) {
                                            WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            result = SmbFileUtil.smbUploading(newFile, tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                            AtsFilePath = tmpByDate + new File(newFile).getName();
                                        } else if ("localhost".equals(uploadType)) {
                                            String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                            WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                            result = FileHelper.copyFile(newFile, shareDir + tmpByDate + file);
                                            AtsFilePath = tmpByDate + file;
                                        } else {
                                            tmpByDate = tmpByDate.replaceAll(reqHeader.bankCode + "/", "");
                                            WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            Map<String, String> map = FormSubmit.fileUpload(FGBiz.dspCenter.dspSet.receiptShareDir, actNum, newFile, tmpByDate, fileName, getCharset());
                                            WriteBankLogStep3(JSON.toJSONString(map));
                                            if (map.keySet().size() != 0) {
                                                result = Integer.valueOf(map.get("respCode"));
                                                tmpByDate = map.get("remotePath");
                                                AtsFilePath = tmpByDate;
                                            } else {
                                                result = -1;
                                            }
                                        }
                                    } else {
                                        //ftp服务器
                                        FtpSet ftpSet2 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                        WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet2.upDir);
                                        //上传ftp服务器的地址
                                        filePath2 = tmpByDate + new File(newFile).getName();
                                        ftpFilePath = StringHelper.trimEndFileSp(ftpSet2.upDir) + "/" + filePath2;
                                        WriteBankLogLn("开始将回单" + newFile + "上传至" + ftpFilePath);
                                        //上传至ftp
                                        result = FtpUtil.ftpUploading(ftpSet2, newFile, ftpFilePath);
                                    }
                                }
                                String[] receiptFileName_no = file.split("_");
                                if (result == 0 || result == 1) {
                                    tmpFileCount++;
                                    if (result == 0) {
                                        WriteBankLogLn("文件上传成功");
                                    } else {
                                        WriteBankLogLn("文件已存在共享目录无需重复上传");
                                    }
                                    //推送数据给ATS处理
                                    json = new StringBuilder();
                                    json.append("{");
                                    json.append("\"actNum\":\"" + actNum + "\",");
                                    json.append("\"actCur\":\"" + actCur + "\",");
                                    if (getReceiptCodeTime(receiptCodeTime)) {
                                        json.append("\"receiptCode\":\"" + actNum + "_" + receiptFileName_no[1].replace(".pdf", "") + "\",");// 回单编号
                                    } else {
                                        json.append("\"receiptCode\":\"" + receiptFileName_no[1].replace(".pdf", "") + "\",");// 回单编号
                                    }
                                    json.append("\"receiptType\":\"" + "" + "\",");// 回单类型 1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                    json.append("\"receiptState\":\"" + "" + "\",");// 回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                    json.append("\"oppActName\":\"" + "" + "\",");
                                    json.append("\"oppActNum\":\"" + "" + "\",");
                                    json.append("\"amount\":\"" + "" + "\",");
                                    json.append("\"moneyway\":\"" + 1 + "\",");
                                    json.append("\"tranSeqNo\":\"" + receiptFileName_no[1].replace(".pdf", "") + "\",");
                                    json.append("\"tranCode\":\"" + "" + "\",");// 交易码?
                                    json.append("\"tranDate\":\"" + receiptFileName_no[0] + "\",");
                                    if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                        json.append("\"filePath\":\"" + AtsFilePath + "\",");
                                    } else {
                                        json.append("\"filePath\":\"" + filePath2 + "\",");//文件路径
                                    }
                                    json.append("\"fileType\":\"1\"");
                                    json.append("},");
                                    jsonList.add(json);
                                } else {
                                    WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                }
                                if (FileHelper.deleteFileIfExists(newFile)) {
                                    WriteBankLogLn("已删除临时文件：" + newFile);
                                }
                            }
                        }
                        //删除临时文件
                        String path = file_p.getPath().replace(".pdf", "");
                        if (PdfGenerateUtil.deleteFile(new File(path))) {
                            WriteBankLogLn("已删除临时文件夹：" + path);
                        }
                    }
                } else {
                    WriteBankLogLn("文件不存在：" + fileList.get(i).getPath());
                }
            }
            if (tmpFileCount > 0 && jsonList.size() > 0) {
                String sendStr = null;
                if (this.getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                    sendStr = "tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[";
                } else {
                    sendStr = "transType=downloadreceipt&data={\"rows\":[";
                }
                StringBuilder sendJson = new StringBuilder();
                String strValue = bankFront.getStrValueByFor("receiptDataCount", "");
                if (StringHelper.isNullOrEmpty(strValue)) {
                    strValue = "500";
                }
                Integer receiptDataCount = Integer.valueOf(strValue);
                for (int i = 0; i < jsonList.size(); i++) {
                    if ((i + 1) % receiptDataCount == 0 || i == jsonList.size() - 1) {
                        jsonList.get(i).deleteCharAt(jsonList.get(i).length() - 1);
                        sendJson.append(jsonList.get(i));
                        sendJson.append("]}");

                        String[] data;
                        String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                        //宁波银行专用
                        if ("nbGateway".equals(receiptPushType)) {
                            WriteBankLogLn("3.推送给网关的数据" + sendStr + sendJson.toString());
                            DirectBase tmplogMsg = new DirectBase();
                            data = FormSubmit.receiptInfoSend(sendStr + sendJson.toString(), tmplogMsg, false);
                            WriteBankLogLn(tmplogMsg.getSbLog());
                            if (data[0].length() == 0 && data[1].equals("ok")) {
                                WriteBankLogLn("5.推送数据到网关成功" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            } else {
                                WriteBankLogLn("5.推送数据到网关失败" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            }
                        } else {
                            WriteBankLogLn("3.推送给ATS的数据" + sendStr + sendJson.toString().toString());
                            data = sendToATS(sendStr + sendJson.toString().toString());
                            if (data[0].length() == 0 && data[1].equals("ok")) {
                                WriteBankLogLn("5.推送数据到ATS成功" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            } else {
                                WriteBankLogLn("5.推送数据到ATS失败" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                            }
                        }

                        sendJson = new StringBuilder();
                    } else {
                        sendJson.append(jsonList.get(i));
                    }
                }
                WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }
            /*if (tmpFileCount > 0) {
                //返回ATS回单信息
                json.deleteCharAt(json.length() - 1);
                json.append("]}");
                String[] data = sendToATS(json.toString());
                WriteBankLogLn(json.toString());
                if (data[0].length() == 0 && "ok".equals(data[1])) {
                    WriteBankLogLn("推送数据到ATS成功,请查看数据" + json.toString());
                } else {
                    WriteBankLogLn("推送数据到ATS失败");
                }
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }*/
        } catch (Exception e) {
            WriteBankLogLn(e);
        }

    }

    /**
     * 下载文件
     *
     * @throws Exception
     */
    private List<File> downloadFile(FtpSet ftpSet) throws Exception {
        String chars = ".zip";
        if (this.getBankConfig().getValueAsBool("isReceiptInterface")) {
            chars = ".pdf";
        }
        List<File> fileList = new ArrayList<File>();
        Map<String, Object> jschMap = getChannel(ftpSet);
        //进行文件传输操作：put()、get()....
        ChannelSftp channel = (ChannelSftp) jschMap.get("channel");
        Vector vector = channel.ls(ftpSet.downDir);
        String fileStr = Format.Date8Format.format(new Date());
        StringBuilder fileNameStr = new StringBuilder();
        String filePath = receiptSaveToMainDir + File.separator + reqHeader.bankCode + File.separator + fileStr + ".txt";
        String fileContent = "";
        if (FileHelper.existFile(filePath)) {
            fileContent = FtpUtil.getTextFromFile(filePath, getCharset());
        }
        File file;
        for (int i = 0; i < vector.size(); i++) {
            String dirPath = "";//ftp目录
            String fileName = "";//文件路径
            ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) vector.get(i);
            if (!fileContent.contains(lsEntry.getFilename()) && lsEntry.getFilename().contains(fileStr) && lsEntry.getFilename().contains(chars)) {
//                channel.get(lsEntry.getFilename(), receiptSaveToMainDir);//下载
                if ("/".equals(ftpSet.downDir) || "\\".equals(ftpSet.downDir)) {//只有根目录
                    dirPath = lsEntry.getFilename();
                } else {
                    if (ftpSet.downDir != null && ftpSet.downDir.length() > 0) {
                        if (ftpSet.downDir.contains("/")) {
                            dirPath = ftpSet.downDir + "/" + lsEntry.getFilename();
                        } else if (ftpSet.downDir.contains("\\")) {
                            dirPath = ftpSet.downDir + "\\" + lsEntry.getFilename();
                        }
                    }
                }
                channel.get(dirPath, receiptSaveToMainDir);//下载
                String minDir = StringHelper.trimEndFileSp(receiptSaveToMainDir);
                if ("/".equals(minDir) || "\\".equals(minDir)) {
                    fileName = minDir + lsEntry.getFilename();
                } else {
                    if (minDir.contains("/")) {
                        fileName = minDir + "/" + lsEntry.getFilename();
                    } else if (minDir.contains("\\")) {
                        fileName = minDir + "\\" + lsEntry.getFilename();
                    }
                }
                file = new File(fileName);
                fileList.add(file);
                fileNameStr.append(lsEntry.getFilename()).append("，");
            }
        }

        WriteBankLogLn("SFTP下载服务器文件成功：" + fileList.size() + "笔至本地文件" + receiptSaveToMainDir + "，下载的文件名称为：" + fileNameStr.toString());
        closeChannel((Session) jschMap.get("session"), (ChannelSftp) jschMap.get("channel"));
        generateHisFileName(fileNameStr.toString());
        return fileList;
    }

    private Map<String, Object> getChannel(FtpSet ftpSet) throws Exception {
        Map<String, Object> jschMap = new HashMap<String, Object>();
        WriteBankLogLn("SFTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
        //1、创建JSch类
        JSch jsch = new JSch();
        //2、创建本次的文件传输会话对象，并连接到SFTP服务器。
        Session session = jsch.getSession(ftpSet.userName, ftpSet.serverIP, ftpSet.port); // 根据用户名，主机ip，端口获取一个Session对象
        session.setPassword(ftpSet.userPassword); // 设置密码
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties
        session.setTimeout(ftpSet.timeout); // 设置timeout时间
        session.connect(); // 通过Session建立链接
        //3、在该session会话中开启一个SFTP通道，之后就可以在该通道中进行文件传输了
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.connect();
        jschMap.put("session", session);
        jschMap.put("channel", channelSftp);
        return jschMap;
    }

    private void closeChannel(Session session, ChannelSftp channel) throws Exception {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }


    private void generateHisFileName(String fileNameStr) throws Exception {
        FileOutputStream fos = null;
        try {

            String tmpByDate = Format.Date8Format.format(new Date());
            String filePath = receiptSaveToMainDir + File.separator + reqHeader.bankCode + File.separator + tmpByDate + ".txt";
            File batFile = new File(filePath);
            if (!batFile.getParentFile().exists()) {
                batFile.getParentFile().mkdirs();
            }
            String fileContent = "";
            if (!batFile.exists()) {
                batFile.createNewFile();
            } else {
                fileContent = FtpUtil.getTextFromFile(filePath, getCharset());
                if (fileContent.contains(fileNameStr)) {
                    return;
                }
            }
            fos = new FileOutputStream(batFile);
            fos.write(fileContent.concat(fileNameStr).getBytes());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }

    public void qryCodeFile() {
        try {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.codeMainDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.codeShareDir)) {
                    if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.codePushServerUrl)) {
                        download_b2e0043();
                    } else {
                        WriteBankLogLn("DSPSystem未配置行号更新文件推送地址");
                    }
                } else {
                    WriteBankLogLn("DSPSystem未配置行号更新文件共享目录");
                }
            } else {
                WriteBankLogLn("DSPSystem未配置行号更新文件下载保存主目录");
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        }
    }

    private void download_b2e0043() throws Exception {
        //统计更新成功文件数量
        int count = 0;
        //记录成功处理文件的名称
        List<String> list = new ArrayList<String>();
        //记录成功上传文件的名称
        StringBuilder sd = new StringBuilder();
        //定义返回ATS的json字符串
        StringBuilder json = new StringBuilder();
        json.append("transType=downloadCodeFile&data={\"rows\":[");
        //获取待下载的行号更新文件
        String path = FGBiz.dspCenter.dspSet.codeMainDir + "/" + "b2e0043";
        File file = new File(path);
        File[] tempList = file.listFiles();
        if (tempList == null || tempList.length == 0) {
            WriteBankLogLn("文件夹没有需要下载行号更新的文件" + path);
            return;
        }
        //开始去前置机目录获取文件
        for (File files : tempList) {
            String[] fileContent = files.getName().replaceAll(".txt", "").split("_");
            if (fileContent.length == 2) {
                String fileType = fileContent[0];//文件类型
                String dateTime = fileContent[1];//请求时间
                String fileName = "";
                switch (Integer.parseInt(fileType)) {
                    case 0:
                        fileName = "cnap.zip";
                        break;
                    case 1:
                        fileName = "domestic.zip";
                        break;
                    case 2:
                        fileName = "cdsCnap.zip";
                        break;
                    default:
                        fileName = "";
                }
                if (StringHelper.hasAnyChar(fileName)) {
                    int result = -1;//下载前置机目录标识
                    //行号更新文件本地存放位置
                    String localFilePath = FGBiz.dspCenter.dspSet.codeMainDir + "/" + dateTime.substring(0, 8) + "/"
                            + reqHeader.bankCode + "/" + fileType + "/" + dateTime.substring(8) + "/";
                    String localCsvFilePath = FGBiz.dspCenter.dspSet.codeMainDir + "/" + dateTime.substring(0, 8) + "/"
                            + reqHeader.bankCode + "/" + "csv" + "/" + dateTime.substring(8) + "/";
                    //前置机存放下载文件目录
                    String codeFilePath = StringHelper.trimEndFileSp(bankFront.bankReceiptMainDir) + "/";
                    //File codeFile=new File(codeFilePath);
                    //if(codeFile.exists()){
                    WriteBankLogLn("正在从前置机目录下载文件：" + fileName);
                    StringBuilder sbd = new StringBuilder();
                    if (!FileHelper.existFile(localFilePath + fileName)) {
                        result = SmbFileUtil.smbDownloadInChar(localFilePath, codeFilePath, fileName, sbd);
                        if (result == 1) {//下载成功
                            //行号更新文件处理后存放位置
                            String manageFilePath = FGBiz.dspCenter.dspSet.codeMainDir + "/" + dateTime.substring(0, 8) + "/"
                                    + reqHeader.bankCode + "/" + "manege" + "/" + dateTime.substring(8) + "/";
                            if (FileHelper.existFile(localFilePath + fileName)) {
                                //开始解压文件
                                ZipHelper.unZipFiles(localFilePath + fileName, localCsvFilePath);
                                //开始处理文件
                                for (File file2 : new File(localCsvFilePath).listFiles()) {
                                    if (file2.getName().contains(".csv")) {
                                        boolean isSuccess = false;//处理文件标识
                                        String manageFilePath2 = manageFilePath + file2.getName();
                                        List<String> dataList = CSVUtils.exportCsv(file2.getPath(), getCharset());
                                        List<String> dataList2 = new LinkedList<String>();
                                        if (dataList != null && !dataList.isEmpty()) {
                                            StringBuilder stringBuilder = null;
                                            WriteBankLogLn("行号更新文件" + file2.getPath() + "开始处理文件");
                                            for (int i = 0, length = dataList.size(); i < length; i++) {
                                                String content = dataList.get(i);
                                                String[] dataArray = content.split(",");
                                                if (dataArray.length >= 2) {
                                                    if (i == 0) {
                                                        stringBuilder = new StringBuilder();
                                                        stringBuilder.append(dataArray[0]).append("," + dataArray[1]).append(",银行ID").append(",区域ID");
                                                        dataList2.add(stringBuilder.toString());
                                                    } else {
                                                        String dataArray0 = dataArray[0].replaceAll("\t", "").replaceAll("\"", "");
                                                        if (dataArray0.length() >= 12) {
                                                            String bankId = "\"" + dataArray0.substring(0, 3) + "\"\t";//增加制表符
                                                            String areaCode = dataArray0.substring(3, 7);
                                                            //获取areaId
                                                            String areaId = getBankAreaConfig().getMapKeyByValue("areaIdMapping", areaCode);
                                                            if (areaId.length() == 6) {
                                                                areaId = "\"" + areaId.substring(0, 4) + "\"\t";//增加制表符
                                                            }
                                                            stringBuilder = new StringBuilder();
                                                            stringBuilder.append(dataArray[0]).append("," + dataArray[1]).append("," + bankId).append("," + areaId);
                                                            dataList2.add(stringBuilder.toString());
                                                        } else {
                                                            dataList2.add(content);
                                                        }
                                                    }
                                                } else {
                                                    dataList2.add(content);
                                                }
                                            }
                                            if (dataList2 != null) {
                                                isSuccess = CSVUtils.importCsv(manageFilePath2, dataList2, getCharset());
                                                if (isSuccess) {
                                                    WriteBankLogLn("行号更新文件" + localFilePath + "处理成功，存放路径：" + manageFilePath2);
                                                    list.add(manageFilePath2);
                                                } else {
                                                    WriteBankLogLn("行号更新文件" + localFilePath + "处理失败");
                                                }
                                            }
                                        }
                                    }
                                }
                                int uploadResult = -1;//上传共享目录标识
                                //行号更新文件共享目录存放位置
                                String smbFilePath = dateTime.substring(0, 6) + "/" + dateTime.substring(6, 8) + "/"
                                        + reqHeader.bankCode + "/" + fileType + "/" + dateTime.substring(8) + "/";
                                //处理完成，开始上传处理后的文件到dsp共享目录
                                if (list.size() > 0) {
                                    for (String filePath : list) {
                                        uploadResult = SmbFileUtil.smbUploadingInChar(filePath, smbFilePath, FGBiz.dspCenter.dspSet.codeShareDir);
                                        //上传成功处理
                                        if (uploadResult == 0 || uploadResult == 1) {
                                            if (uploadResult == 0) {
                                                WriteBankLogLn("文件上传成功：" + FGBiz.dspCenter.dspSet.codeShareDir + smbFilePath);
                                            } else {
                                                WriteBankLogLn("文件已存在共享目录无需重复上传" + FGBiz.dspCenter.dspSet.codeShareDir + smbFilePath);
                                            }
                                            //推送数据给ATS处理
                                            json.append("{");
                                            json.append("\"bankCode\":\"" + reqHeader.bankCode + "\",");//渠道指令代码
                                            json.append("\"dateTime\":\"" + dateTime + "\",");//请求下载时间
                                            json.append("\"filePath\":\"" + smbFilePath + new File(filePath).getName() + "\",");//文件路径
                                            json.append("\"fileType\":\"" + fileType + "\"");//文件类型
                                            json.append("},");
                                            //记录上传成功文件
                                            sd.append(new File(filePath).getName() + ",");
                                            count++;
                                        }
                                    }
                                }
                                WriteBankLogLn("成功保存了" + count + "个文件,文件名为：" + sd);
                                if (count > 0) {
                                    json.deleteCharAt(json.length() - 1);
                                    json.append("]}");
                                    WriteBankLogLn("推送数据到ATS的数据为：" + json.toString());
                                    String[] data = sendToATSIsCode(json.toString());
                                    if (data[0].length() == 0 && data[1].equals("ok")) {
                                        WriteBankLogLn("推送数据到ATS成功,请查看数据");
                                        if (FileHelper.deleteFileIfExists(files.getPath())) {
                                            WriteBankLogLn("文件" + files.getPath() + "处理完成，已删除");
                                        }
                                    } else {
                                        WriteBankLogLn("推送数据到ATS失败");
                                    }
                                }
                            } else {
                                WriteBankLogLn("从前置机目录下载文件异常：" + sbd);
                            }
                        } else {
                            WriteBankLogLn("从前置机目录下载文件失败：" + sbd);
                        }
                    } else {
                        WriteBankLogLn(localFilePath + fileName + "文件已更新，如需重新下载，请删除此文件");
                    }
                } else {
                    WriteBankLogLn(fileType + "文件类型有误");
                }
            }
        }
    }

    //当前时间是否大于设置时间
    public boolean getReceiptCodeTime(String time) throws Exception {
        boolean isStart = false;
        if (!StringHelper.isNullOrEmpty(time)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = format.parse(time);
            Long timestamp = date.getTime();
            Date nowDate = new Date();
            if (nowDate.getTime() >= timestamp) {
                isStart = true;
            }
        }
        return isStart;
    }
}